package com.zj.chat.common.websocket;

import cn.hutool.json.JSONUtil;
import com.zj.chat.common.websocket.domain.enums.WSBRespTypeEnum;
import com.zj.chat.common.websocket.domain.vo.req.WSBaseReq;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.util.Arrays;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName NettyWebsocketServerHandler
 * @Description
 * @createTime 2025年01月27日 19:33
 */
public class NettyWebsocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        WSBaseReq bean = JSONUtil.toBean(text, WSBaseReq.class);
        WSBRespTypeEnum typeEnum = Arrays.stream(WSBRespTypeEnum.values()).filter(v -> v.getType().equals(bean.getType())).findFirst().orElse(null);
        channelHandlerContext.channel().writeAndFlush("let us go");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
            System.out.println("握手完成");
        }else if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                System.out.println("读空闲");
                //todo 用户下线
                ctx.channel().close();
            }
        }
    }
}
